package org.acsis.jee.util;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	
	private static Configuration configuration;
	private static SessionFactory sessionFactory;
	private static Logger log = Logger.getLogger(HibernateUtil.class);
	private static Session s;
	public static Session getSession(){
		
		try {
			
			if(sessionFactory == null){
				configuration = new Configuration();
				sessionFactory = configuration.configure().buildSessionFactory();
			}
			
			s = sessionFactory.openSession();
		} 
		catch (Throwable ex) {
			log.error("Building SessionFactory failed.", ex);
			throw new ExceptionInInitializerError(ex);
		}
		
		return s;
	}
	
	public static Session getCurrentSession(){
		return s;
	}
	
	public static SessionFactory newSessionFactory(final String pathToHibernateCfgXml) {  
        log.info("Loading Hibernate Session Factory with configurations from file "   
                + pathToHibernateCfgXml + "...");  
        Configuration hibernateConfiguration = new Configuration();  
        hibernateConfiguration.configure(pathToHibernateCfgXml);  
        return hibernateConfiguration.buildSessionFactory();  
    }  
	
	public static Session getTestSession(){
		
		
		Configuration hibernateConfiguration = new Configuration();  
        hibernateConfiguration.configure("hibernate.test.cfg.xml");
        s = hibernateConfiguration.buildSessionFactory().openSession();
        return s;
	}
}
